Ext.namespace('SpeciesObservation');

SpeciesObservation.speciesGrid = function(config) {
	
	this.store = new Ext.data.JsonStore({
			url: Config.baseUrl + 'resources/api/api.php'
		,	baseParams: { 
				cmd: 'listData'
			}
		,	root: 'data'
		,	totalProperty: 'totalCount'
		,	fields: [	
					{name: 'id', mapping: 'id'}
				,	{name: 'auth', mapping: 'auth'}	
				,	{name: 'imageId', mapping: 'imageId'}
				,	{name: 'sex', mapping: 'sex'}
				,	{name: 'age', mapping: 'age'}
				,	{name: 'county', mapping: 'county'}
				,	{name: 'numberSeen', mapping: 'numberSeen'}
				,	{name: 'vernacularName', mapping: 'vernacularName'}
				,	{name: 'state', mapping: 'state'}
				,	{name: 'dateObserved', type:'date', dateFormat: 'Y-m-d h:i:s'}
//				,	{name: 'dateObserved', type:'date'}
				,	{name: 'verbatimDate', mapping: 'verbatimDate'}
				,	{name: 'locality', mapping: 'locality'}
				,	{name: 'contactInfo', mapping: 'contactInfo'}
				,	{name: 'description', mapping: 'description'}
				,	{name: 'observers', mapping: 'observers'}
				,	{name: 'stage', mapping: 'stage'}
				,	{name: 'lastModified', mapping: 'lastModified'}
				,	{name: 'scientificName', mapping: 'scientificName'}
				,	{name: 'sightRec', mapping: 'sightRec'}
				,	{name: 'specimen', mapping: 'specimen'}
				,	{name: 'heardOnly', mapping: 'heardOnly'}
				,	{name: 'photo', mapping: 'photo'}
				,	{name: 'photoUri', mapping: 'photoUri'}
				,	{name: 'videoUri', mapping: 'videoUri'}
				,	{name: 'video', mapping: 'video'}
				,	{name: 'audioRecUri', mapping: 'audioRecUri'}
				,	{name: 'audioRec', mapping: 'audioRec'}
				,	{name: 'characteristics', mapping: 'characteristics'}
				,	{name: 'significance', mapping: 'significance'}
				,	'filename'
				,	'path'
				,	'filename2'
				,	'path2'
				,	'filename3'
				,	'path3'
				,	'filename4'
				,	'path4'
				,	'filename5'
				,	'path5'
				,	'historicalCard'
				,	'public'
			]			
		,	remoteSort: true
		,	sortInfo: { field: "lastModified", direction: "DESC" }
		,	listeners: {
				loadexception: function() {
					SpeciesObservation.Notice.msg('Error','Error in connection.');
				}
			}

	});

	this.filters = new Ext.ux.grid.GridFilters({
			encode: true
		,	filters: [{
					type: 'string'
				,	dataIndex: 'vernacularName'
			}, {
					type: 'string'
				,	dataIndex: 'county'
			}, {
					type: 'string'
				,	dataIndex: 'locality'
			}, {
					type: 'string'
				,	dataIndex: 'state'
			},{
					type: 'date'
				,	dataIndex: 'dateObserved'
			},{
					type: 'date'
				,	dataIndex: 'lastModified'
			},{
					type: 'string'
				,	dataIndex: 'description'
			},{
					type: 'list'
				,	dataIndex: 'sex'
				,	options: ['Male', 'Female']
				,	phpMode: true
			},{
					type: 'list'
				,	dataIndex: 'age'
				,	options: ['Adult', 'Juvenile']
				,	phpMode: true
			},{
					type: 'list'
				,	dataIndex: 'historicalCard'
				,	options: ['Card', 'Form']
				,	phpMode: true
			},{
					type: 'list'
				,	dataIndex: 'stage'
				,	options: ['Approved', 'Pending', 'Declined']
				,	phpMode: true
			},{
					type: 'boolean'
				,	dataIndex: 'sightrec'
			},{
					type: 'boolean'
				,	dataIndex: 'photo'	
			},{
					type: 'boolean'
				,	dataIndex: 'specimen'	
			},{
					type: 'boolean'
				,	dataIndex: 	'heardonly'
			},{
					type: 'boolean'
				,	dataIndex: 	'video'
			},{
					type: 'boolean'
				,	dataIndex: 	'audiorec'
			}]
	});
	
	var sightrec = new Ext.grid.CheckColumn({
			header: 'Sight Rec'
		,	dataIndex: 'sightRec'
		,	width: 50
		,	sortable: true
	});

	var videoColumn = new Ext.grid.CheckColumn({
			header: 'Video'
		,	dataIndex: 'video'
		,	width: 35
		,	sortable: true
		,	renderer: this.renderVideo
	});

	var audiorec = new Ext.grid.CheckColumn({
			header: 'Audio Rec.'
		,	dataIndex: 'audioRec'
		,	width: 55
		,	sortable: true
		,	renderer: this.renderAudio
	});

	var photoColumn = new Ext.grid.CheckColumn({
			width: 35
		,	header: 'Photo'
		,	dataIndex: 'photo'
		,	sortable: true
		,	renderer: this.renderPhoto
	});

	var specimenColumn = new Ext.grid.CheckColumn({
			width: 45
		,	header: 'Specimen'
		,	dataIndex: 'specimen'
		,	sortable: true
	});

	var heardonly = new Ext.grid.CheckColumn({
			header: 'Heard'
		,	dataIndex: 'heardOnly'
		,	width: 55
		,	sortable: true
	});

	this.menuItem = [{
			text: 'CSV'
		,	iconCls: 'icon_csv'
		,	scope: this
		,	handler: function(){
				this.getObservation('getCsv');
			}	
	}, {
			text: 'DarwinCore Archive'
		,	iconCls: 'icon_zip'
		,	scope: this
		,	handler: function(){
				this.getObservation('buildDWCA');
			}
	}, {
			text: '3x5 PDF'
		,	iconCls: 'icon_adobe'
		,	scope: this
		,	handler: function(){
				this.getObservation('getPdf');
			}
	}]

	this.expander = new Ext.ux.grid.RowExpander({
		tpl: new Ext.XTemplate(
				'<tpl for".">'
			,	'<div style="padding-left:4px; padding-bottom:2px;">'
			,	'<tpl if="numberSeen != 0"><div><b>Number Seen: </b> {numberSeen}</div></tpl>'
			,	'<tpl if="characteristics != 0"><div><b>Plumage Characteristics: </b> {characteristics}</div></tpl>'
			,	'<tpl if="observers != 0"><div><b>Observers: </b> {observers}</div></tpl>'
			,	'<tpl if="verbatimDate != 0"><div><b>Verbatim Date: </b> {verbatimDate}</div></tpl>'
			,	'<tpl if="significance != 0"><div><b>Significance: </b> {significance}</div></tpl>'
//			,	'<tpl if="contactInfo != 0"><div><b>Contact Infomation: </b> {contactInfo}</div></tpl>'
			,	'<tpl if="description != 0"><div><b>Description: </b> {description}</div></tpl>'
			,	'</div>'
			,	'</tpl>'
		)
	});

	this.sm = new Ext.grid.RowSelectionModel({singleSelect:true});

	Ext.apply(this, config, {
			border: false		
		,	ref: 'refmyGrid'
		,	store: this.store
		,	autoScroll: true
		,	sm: this.sm
		,	loadMask: true
		,	plugins: [this.filters, this.expander]
		,	publicView: false
		,	columns: [
					this.expander
			,{
					header: "Card"
				,	dataIndex: 'historicalCard'
				,	width: 35
				,	sortable: false
				,	hidden: true
				,	id: 'cardId'
				,	renderer: this.historicalCard
			},{
					header: "Scientific Name"
				,	dataIndex: 'scientificName'
				,	width: 120
				,	sortable: false
			},{
					header: "English Name"
				,	dataIndex: 'vernacularName'
				,	width: 120
				,	sortable: true
			},{
					header: "Date Observed"
				,	dataIndex: 'dateObserved'
				,	width: 80
				,	sortable: true
				,	format: 'Y-m-d'
				,	xtype: 'datecolumn'				
			},{
					header: "Sex"
				,	dataIndex: 'sex'
				,	width: 45
				,	sortable: true
			},{
					header: "Age"
				,	dataIndex: 'age'
				,	width: 50
				,	sortable: true
			},{
					header: "County"
				,	dataIndex: 'county'
				,	width: 100
				,	sortable: true
			},{
					header: "State"
				,	dataIndex: 'state'
				,	width: 80
				,	hidden: true
				,	sortable: true
			},{
					header: "Locality"
				,	dataIndex: 'locality'
				,	width: 80
				,	sortable: true
			}
			, sightrec
			,	specimenColumn
			,	heardonly
			,	photoColumn
			,	videoColumn
			,	audiorec
			, {
					header: "Stage"
				,	dataIndex: 'stage'
				,	width: 50
				,	hidden: true
				,	id: 'stageid'
				,	sortable: true
			}, {
					header: "Public"
				,	dataIndex: 'public'
				,	id: 'publicId'
				,	width: 35
				,	hidden: true
			},{
					header: "Last Modified"
				,	dataIndex: 'lastModified'
				,	width: 120
				,	hidden: true
				,	sortable: true
				,	id: 'lastModifiedId'
				,	renderer: this.renderDate 
			}]
		,	viewConfig: {	
					emptyText: 'No Observations Available.'
				,	forceFit: false
			}
		,	bbar: new Ext.PagingToolbar({
					pageSize: 50
				,	store: this.store
				,	displayInfo: true
				,	displayMsg: 'Displaying Observations {0} - {1} of {2}'
				,	emptyMsg: 'No Observations Available.'
				,	items: ['-',{
						text: 'Export...'
					,	tooltip: 'Export observations.'
					, 	iconCls: 'icon_download'
					,	menu: {
							items: this.menuItem
						}
					}]		
			})

	});
	
	SpeciesObservation.speciesGrid.superclass.constructor.call(this, config);
} 
 
Ext.extend(SpeciesObservation.speciesGrid, Ext.grid.GridPanel, {
		renderDate: function( value ) {
				if ( value == '0000-00-00') {
					return('');
				} else {
					return value;
				}
		}

	,	historicalCard: function(value, check, data){
			if(value == true){
				return ('<div class="historicalCard" ext:qtip="' + data.id + '" align="center">&nbsp;</div>');	
			} else {
				return ('<div class="webLink" ext:qtip="' + data.id + '" align="center">&nbsp;</div>');	
			}
		}

	,	renderAudio: function(value, check, data){
			var uri = data.data.audioRecUri;
			if(value == 'on' || value == true){
				return (Ext.isEmpty(uri) ? '<div class="x-grid3-check-col-on">&nbsp;</div>' : String.format('<a href="{0}" target="_blank" title="Click to view audio"><div class="webLink" align="center">&nbsp;</div></a>', uri) );	
			} else {
				return (Ext.isEmpty(uri) ? '<div class="x-grid3-check-col">&nbsp;</div>' : String.format('<a href="{0}" target="_blank" title="Click to view audio"><div class="webLink" align="center">&nbsp;</div></a>', uri) );	
			}
		}

	,	renderPhoto: function(value, check, data){
			var uri = data.data.photoUri;
			if(value == 'on' || value == true){
				return (Ext.isEmpty(uri) ? '<div class="x-grid3-check-col-on">&nbsp;</div>' : String.format('<a href="{0}" target="_blank" title="Click to view photo"><div class="webLink" align="center">&nbsp;</div></a>', uri) );	
			} else {
				return (Ext.isEmpty(uri) ? '<div class="x-grid3-check-col">&nbsp;</div>' : String.format('<a href="{0}" target="_blank" title="Click to view photo"><div class="webLink" align="center">&nbsp;</div></a>', uri) );	
			}
		}	

	,	renderVideo: function(value, check, data){
			var uri = data.data.videoUri;
			if(value == 'on' || value == true){
				return (Ext.isEmpty(uri) ? '<div class="x-grid3-check-col-on">&nbsp;</div>' : String.format('<a href="{0}" target="_blank" title="Click to view video"><div class="webLink" align="center">&nbsp;</div></a>', uri) );	
			} else {
				return (Ext.isEmpty(uri) ? '<div class="x-grid3-check-col">&nbsp;</div>' : String.format('<a href="{0}" target="_blank" title="Click to view video"><div class="webLink" align="center">&nbsp;</div></a>', uri) );	
			}
		}

	,	showContextMenu: function(grid, row, e){
			grid.getSelectionModel().selectRow(row);
			var record = grid.getSelectionModel().getSelected().data
				,	search = record.scientificName
				,	items = []
				,	queue = (record.historicalCard == "1") ? false : true;
				
			if(!this.publicView){
				items.push({
					text: 'Change Status'
				,	scope: this
				,	ref: 'refStatus'
				,	menu: [{
							text: 'Approved (Public)'
						,	scope: this
						,	group: 'status'
						,	checked: false
						,	ref: 'refApproved'
						,	stage: 'Approved'
						,	public: 1
						,	checkHandler: this.onItemCheck
					}, {
							text: 'Approved (Private)'
						,	scope: this
						,	group: 'status'
						,	checked: false					
						,	ref: 'refApproved'
						,	stage: 'Approved'
						,	checkHandler: this.onItemCheck
					}, {
							text: 'Pending'
						,	group: 'status'
						,	scope: this
						,	checked: false
						,	ref: 'refPending'
						,	stage: 'Pending'
						,	checkHandler: this.onItemCheck
					}, {
							text: 'Declined'
						,	group: 'status'
						,	checked: false
						,	scope: this
						,	ref: 'refDeclined'
						,	stage: 'Declined'
						,	checkHandler: this.onItemCheck
					}]	
				},{
						text: 'Send back to Queue'
					,	iconCls: 'icon_undo'
					,	ref: 'refQueue'
					,	scope: this
					,	hidden: queue
					,	handler: this.sendToQueue
				});
			}
			items.push({
				text: 'Export...'
			, 	iconCls: 'icon_download'
			,	scope: this
			,	ref: '../export'
			,	menu: {
					items: this.menuItem
				}
			},'-', {
				text: 'EOL'
			,	iconCls: 'icon_eol'	
			,	scope: this	
			,	handler: function() { 
					window.open('http://www.eol.org/search?q='+search, '_blank');
				}  
			}, {
				text: 'Wikispecies'
			,	iconCls: 'icon_wiki'	
			,	scope: this	
			,	handler: function() { 
					window.open('http://species.wikimedia.org/wiki/'+search, '_blank');
				}  
			}, {
				text: 'GBIF'
			,	scope: this
			,	iconCls: 'icon_gbif'
			,	handler: function() { 
					window.open('http://data.gbif.org/search/'+search, '_blank');
				}  
			}, {
				text: 'GBIF - Checklist Bank'
			,	scope: this
			,	iconCls: 'icon_gbif'
			,	handler: function() { 
					window.open('http://ecat-dev.gbif.org/search?q='+search+'+&rkey=1', '_blank');
				}  
			}, '-', {
				text: 'Google Images'
			,	scope: this
			,	iconCls: 'icon_google'
			,	handler: function() { 
					window.open('http://images.google.com/images?q='+search, '_blank');
				} 
			}, {
				text: 'Flickr'
			,	scope: this
			,	iconCls: 'icon_flickr'	
			,	handler: function() { 
					window.open('http://www.flickr.com/search/?w=all&q='+search+'&m=text', '_blank');
				} 
			});
			
			var menu = new Ext.menu.Menu({
				items: items
			});
			var xy = e.getXY();
			if(!this.publicView){
				switch(record.stage){
					case 'Approved':
						menu.refStatus.menu.refApproved.checked = true;
						break;
					case 'Pending':
						menu.refStatus.menu.refPending.checked = true;
						break;
					case 'Declined':
						menu.refStatus.menu.refDeclined.checked = true;
						break
				}
			}
			menu.showAt(xy);
		}

	,	getObservation: function(cmd){
			if(!Ext.isEmpty(this.getStore().data.items)){
				var d = Ext.get("download");
				if (!Ext.isEmpty(d)) {
					var filter = [];
					var filterData = this.filters.getFilterData();
					if(!Ext.isEmpty(filterData)){
						Ext.each(filterData, function(item){
							filter.push({field: item.field, type: item.data.type, value: item.data.value} );
						});
					}
					if(cmd == 'getPdf'){
						var getSelected = this.getSelectionModel().getSelected();
						var id = (Ext.isDefined(getSelected))? getSelected.data.id : 'all';
						var params = {
							cmd: cmd
						,	id: id
						,	filter: Ext.encode(filter)
						,	public: this.publicView 
						};  
					}else {
						var params = {
							cmd: cmd
						,	filter: Ext.encode(filter)
						,	public: this.publicView
						};
					}
					SpeciesObservation.Notice.msg('Success','Please wait...');
					d.dom.src = Config.baseUrl + 'resources/api/api.php?' + Ext.urlEncode(params);
				} else {
					SpeciesObservation.Notice.msg('Error','Error in exporting...');
				}
			} else {
				SpeciesObservation.Notice.msg('Notice','No Observations Available.');
			}
		}
	,	onItemCheck: function(item, checked){
			if(item.checked){
				var selected = this.getSelectionModel().getSelected().data;
	
				Ext.Ajax.request({
						url: Config.baseUrl + 'resources/api/api.php'
					,	params: { 
								cmd: 'updateStatus'
							,	stage: item.stage
							,	auth: selected.auth
							,	public: item.public || 0
							,	id: selected.id
						}
					,	scope: this	
					,	success: function(response){
							var index = this.getSelectionModel().last;
							var rec = this.store.getAt(index);
							rec.set('stage', item.stage);
							rec.set('public', item.public || 0);
							rec.commit();
							this.store.commitChanges();
							SpeciesObservation.Notice.msg('Success', 'Status changed successfully.');
						}
					,	failure: function(result){
							SpeciesObservation.Notice.msg('Error', 'Error in connection.');
						} 
				}, this);
			}
		}
	,	sendToQueue: function(){
			var selected = this.getSelectionModel().getSelected().data;
			Ext.Ajax.request({
					url: Config.baseUrl + 'resources/api/api.php'
				,	params: { 
							cmd: 'sendToQueue'				
						,	occurrenceId: selected.id
						,	auth: selected.auth
					}
				,	scope: this	
				,	success: function(response){
						var o = Ext.decode(response.responseText);
						if(o.success){
							this.getStore().reload();
							SpeciesObservation.Notice.msg('Success', 'Observation successfully added to queue.');
						} else {
							SpeciesObservation.Notice.msg('Error', 'Error in adding observation to queue.');
						}
					}
				,	failure: function(result){
						SpeciesObservation.Notice.msg('Error', 'Error in connection.');
					} 
			}, this);
		}	
});